package com.elock.service.serviceImpl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.elock.base.core.Filter;
import com.elock.base.core.Page;
import com.elock.base.core.Pageable;
import com.elock.base.core.service.impl.BaseServiceImpl;
import com.elock.dao.ElockDao;
import com.elock.entity.Elock;
import com.elock.entity.ElockRealtimeStatus;
import com.elock.entity.ElockSaleOrg;
import com.elock.entity.SaleOrg;
import com.elock.service.ElockRealtimeStatusService;
import com.elock.service.ElockSaleOrgService;
import com.elock.service.ElockService;
import com.elock.service.SaleOrgBaseService;

/**
 * 锁
 * @author 仁德
 */
@Service("elockServiceImpl")
public class ElockServiceImpl extends BaseServiceImpl<Elock> implements ElockService {

	@Resource(name = "elockRealtimeStatusServiceImpl")
	private ElockRealtimeStatusService elockRealtimeStatusService;
	@Resource(name = "elockDao")
	private ElockDao elockDao;
	@Resource(name = "saleOrgBaseServiceImpl")
	private SaleOrgBaseService saleOrgBaseService;
	@Resource(name = "elockSaleOrgServiceImpl")
	private ElockSaleOrgService elockSaleOrgService;

	@Override
	@Transactional
	public void saveUpdate(Elock elock, Long saleOrgId) {

		if (elock.getId() == null) {
			this.save(elock);

			//锁的实时状态
			ElockRealtimeStatus elockRealtimeStatus = new ElockRealtimeStatus();
			elockRealtimeStatus.setElockId(elock.getId());
			elockRealtimeStatus.setElockNum(elock.getElockNum());
			elockRealtimeStatusService.save(elockRealtimeStatus);
		}
		else {
			this.update(elock);
		}

		//锁机构关联
//		saveElockSaleOrg(saleOrgId, elock);
	}

	/**
	 * 保存锁机构关联
	 */
	public void saveElockSaleOrg(Long saleOrgId, Elock elock) {

		SaleOrg saleOrg = saleOrgBaseService.find(saleOrgId);
		List<Filter> filters = new ArrayList<Filter>();
		filters.add(Filter.eq("elock", elock));
		List<ElockSaleOrg> elockSaleOrgs = elockSaleOrgService.findList(null,
				filters,
				null);
		ElockSaleOrg elockSaleOrg = null;
		for (ElockSaleOrg org : elockSaleOrgs) {
			if (saleOrg != null && org.getSaleOrg().equals(saleOrg)) {
				elockSaleOrg = org;
			}
			else {
				elockSaleOrgService.delete(org);
			}
		}
		if (elockSaleOrg == null && saleOrg != null) {
			elockSaleOrg = new ElockSaleOrg();
			elockSaleOrg.setSaleOrg(saleOrg);
			elockSaleOrg.setElock(elock);
			elockSaleOrgService.save(elockSaleOrg);
		}
	}

	@Override
	@Transactional(readOnly = true)
	public Page<Map<String, Object>> findPage(String elockNum, String elockName,
			Long saleOrgId, Boolean isSelect, Pageable pageable) {
		return elockDao.findPage(elockNum, elockName, saleOrgId, isSelect, pageable);
	}

	@Override
	@Transactional(readOnly = true)
	public Elock findByElockNum(String elockNum) {
		return elockDao.findByElockNum(elockNum);
	}
}
